package com.youlu.campus.service.platform;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.AppUserShareActivity;
import com.youlu.campus.entity.VO.req.AppUserShareActivityQueryVO;
import com.youlu.campus.entity.channel.AppChannel;
import com.youlu.campus.entity.commission.DistributorApply;
import com.youlu.campus.entity.commission.DistributorApplyStatusEnum;
import com.youlu.campus.entity.commission.dto.DistributorBuildLinkDTO;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.entity.system.UserDataPermission;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.commission.DistributorApplyService;
import com.youlu.campus.service.system.UserDataPermissionService;
import lombok.extern.slf4j.Slf4j;
import net.polyv.live.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AppUserShareActivityService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private DistributorApplyService distributorApplyService;
    @Autowired
    private UserDataPermissionService userDataPermissionService;

    @Value("${spring.profiles.active}")
    private String env;

    private final String TEST_EVN_DOMAIN = "https://p-test.dreambeat.cn/s/";

    private final String PROD_EVN_DOMAIN = "https://p.ca114.net/s/";

    private static final String HOME_PAGE = "/pages/tabbar/tabbar?activityChannelId=";


    public String getMiniPageUrl(AppChannel appChannel) {
        if (StringUtils.isBlank(appChannel.getActivityId())) {
            return HOME_PAGE + appChannel.getId();
        }
        String activityId = appChannel.getActivityId();
        String id = appChannel.getId();
        ActivityInfo activityInfo = activityService.findOne(appChannel.getActivityId());
        /**
         * 类型
         * jinshuju 金数据
         * continuous-daka 连续打卡
         * timetable 课程表
         * daka 活动打卡
         * douyin 抖音
         * qimobang-video 期末帮视频活动
         * publicity 宣传类活动
         * kos 金山KOS
         * recruitment 实习招聘
         * wx-mini-dreambeat-contest:微信小程序梦想跳动竞赛类,
         * vote:投票,
         * third-video:三方视频类
         * video:视频类,
         * before:之前活动类型,
         * contest-plus:竞赛类,
         * h5-plus:h5新版,
         * qq-mini-plus:小程序活动plus竞赛类
         * qq-mini-plus-noncontest:小程序活动plus非竞赛类
         * qq-mini-zhongqing-contest 中青小程序活动竞赛类型
         * qq-mini-zhongqing-noncontest 中青小程序活动非竞赛类型
         * h5++:新版H5,最终版
         */
        switch (activityInfo.getType()) {
            case "wx-mini-dreambeat-contest":
                return "/pages/contest/detail?activityId=" + activityId + "&activityChannelId=" + id;
            case "video":
                return "/pages/activity/detail?activityId=" + activityId + "&activityChannelId=" + id;
            case "kos":
                return "/pages/kos/kos-detail?activityId=" + activityId + "&activityChannelId=" + id;
            case "daka":
                return "/pages/check-in/detail?activityId=" + activityId + "&activityChannelId=" + id;
            case "recruitment":
                return "/pages/recruitment?activityId=" + activityId + "&activityChannelId=" + id;
            // 连续打卡
            case "continuous-daka":
                return "/pages/continuous-check-in/detail?activityId=" + activityId + "&activityChannelId=" + id;
            default:
                return "/pages/recruitment?activityId=" + activityId + "&activityChannelId=" + id;
        }
    }


    public String getChannelLinkByChannelIdAndActivityId(String channelId, String activityId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(channelId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        AppUserShareActivity appUserShareActivity = this.mongoTemplate.findOne(query, AppUserShareActivity.class);
        if (Objects.isNull(appUserShareActivity)) {
            return "";
        }
        return doBuildLink(appUserShareActivity.getId());
    }

    /**
     * 新增渠道活动链接
     *
     * @param distributorBuildLink
     * @return
     */
    public String buildChannelLink(DistributorBuildLinkDTO distributorBuildLink) {
        String activityId = distributorBuildLink.getActivityId();
        String userId = distributorBuildLink.getUserId();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        AppUserShareActivity appUserShareActivity = this.mongoTemplate.findOne(query, AppUserShareActivity.class);
        if (Objects.nonNull(appUserShareActivity)) {
            return doBuildLink(appUserShareActivity.getId());
        }
        ActivityInfo activityInfo = activityService.findOne(activityId);
        Update update = new Update();
        if (Objects.nonNull(activityInfo)) {
            update.set("activityType", activityInfo.getType());
        }
        update.set("shareLinkType", distributorBuildLink.getShareLinkType());
        update.set("activityChannelId", userId);
        update.set("pageType", distributorBuildLink.getPageType());
        Date now = new Date();
        update.setOnInsert("createdTime", now);
        update.set("updatedTime", now);
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.upsert(Boolean.TRUE);
        findAndModifyOptions.returnNew(Boolean.TRUE);
        AppUserShareActivity appUserShareActivityModify = this.mongoTemplate.findAndModify(query, update,
                findAndModifyOptions, AppUserShareActivity.class);
        return doBuildLink(appUserShareActivityModify.getId());
    }


    public void delete(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        this.mongoTemplate.remove(query, AppUserShareActivity.class);
    }


    public List<AppUserShareActivity> list(String distributorId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(distributorId));
        query.with(Sort.by(Sort.Direction.DESC, "id"));
        List<AppUserShareActivity> list = this.mongoTemplate.find(query, AppUserShareActivity.class);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        list.stream().forEach(appUserShareActivity -> {
            ActivityInfo activityInfo = activityService.findOne(appUserShareActivity.getActivityId());
            if (Objects.nonNull(activityInfo)) {
                appUserShareActivity.setActivityName(activityInfo.getName());
            }
        });
        return list;
    }

    public String buildLink(DistributorBuildLinkDTO distributorBuildLink) {
        String activityId = distributorBuildLink.getActivityId();
        String userId = distributorBuildLink.getUserId();
        String optUserName = distributorBuildLink.getOptUserName();
        log.info("【生成第三方链接】操作人:{}| activityId:{}", optUserName, activityId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        AppUserShareActivity appUserShareActivity = this.mongoTemplate.findOne(query, AppUserShareActivity.class);
        if (Objects.nonNull(appUserShareActivity)) {
            return doBuildLink(appUserShareActivity.getId());
        }
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if (Objects.isNull(activityTaskInfo)) {
            throw new BusinessException("活动邀请任务不存在");
        }
        ActivityInfo activityInfo = activityService.findOne(activityId);
        Update update = new Update();
        update.set("taskId", activityTaskInfo.getId());
        if (StringUtils.isNotBlank(distributorBuildLink.getAppName())) {
            update.set("appName", distributorBuildLink.getAppName());
        }
        DistributorApply distributorApply = distributorApplyService.findByUserId(userId,
                DistributorApplyStatusEnum.PASS.getValue());
        if (Objects.isNull(distributorApply)) {
            throw new BusinessException("当前分销员未审核通过");
        }
        update.set("sharedByOpenId", distributorApply.getOpenId());
        update.set("activityType", activityInfo.getType());
        update.set("shareLinkType", 1);
        Date now = new Date();
        update.setOnInsert("createdTime", now);
        update.set("updatedTime", now);
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.returnNew(Boolean.TRUE);
        findAndModifyOptions.upsert(Boolean.TRUE);
        AppUserShareActivity appUserShareActivityModify = this.mongoTemplate.findAndModify(query, update,
                findAndModifyOptions, AppUserShareActivity.class);
        return doBuildLink(appUserShareActivityModify.getId());
    }

    public Page<AppUserShareActivity> pageList(AppUserShareActivityQueryVO request) {
        log.info(":>>> 查询活动分享链接，参数:{}", JSON.toJSON(request));
        Query query = new Query();
        UserDataPermission userDataPermission = null;
        boolean hasUserId = StringUtils.isNotBlank(request.getUserId());
        List<String> aclAidList = new ArrayList<>();
        if (hasUserId) {
            UserDataPermission req = new UserDataPermission();
            req.setUserId(request.getUserId());
            List<UserDataPermission> datas = userDataPermissionService.list(req);
            if (!org.springframework.util.CollectionUtils.isEmpty(datas) && !org.springframework.util.CollectionUtils.isEmpty(datas.get(0).getActivityId())) {
                userDataPermission = datas.get(0);
                log.info(":>>> 用户:{} 的数据权限权限配置:{}", request.getUserId(),
                        JSON.toJSON(userDataPermission.getActivityId()));
                aclAidList = datas.get(0).getActivityId();
            }
        }
        Criteria criteria = new Criteria();
        if (StringUtils.isNotEmpty(request.getActivityId())) {
            criteria.andOperator(Criteria.where("id").is(request.getActivityId()));
        } else {
            criteria.andOperator(Criteria.where("id").in(aclAidList));
        }
        query.addCriteria(criteria);
        Long count = mongoTemplate.count(query, AppUserShareActivity.class);
        return null;
    }

    private String doBuildLink(String linkId) {
        if (env.startsWith("prod")) {
            return PROD_EVN_DOMAIN + linkId;
        } else if ("beta".equals(env)) {
            return TEST_EVN_DOMAIN + linkId;
        }
        return TEST_EVN_DOMAIN + linkId;
    }
}
